<?php
namespace app\man\controller;


use think\Db;
use think\Cache;
use think\Controller;
use think\Paginator;
use think\Request;
class Auth extends Common
{
	public function index(){
		$page=input('page',1);
		$data = Db::name('auth_account')->order('id desc')->paginate(15,false,['page'=>$page]);
		$this->assign('data',$data);
		return $this->fetch('index');
	}

	public function wechat(){
		$data = Db::table('aicece_wechat_auth')->alias('w')->join('aicece_auth_account a','w.pid=a.id')->field('w.appid,w.status,w.id,a.app_name,w.start_time,w.end_time,w.authorizer_refresh_token')->paginate();

		$this->assign('data', $data);
		return $this->fetch('wechat');
	}
	public function auth_page(){
			$com_appid = input("com_appid");
			$pid = input('pid');
			$appid = input('appid');
			$verify = Db::name('auth_account')->where('com_appid',$com_appid)->find();
			if (!$component_access_token = cache::get('component_access_token_'.$appid)){
	            $data = '{"component_appid":"'.$com_appid.'","component_appsecret":"'.$verify['component_appsecret'].'","component_verify_ticket":"'.$verify['ComponentVerifyTicket'].'"}';
	            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
	            $res = json_decode($this->curl_post($data, $url));
	            $component_access_token = $res->component_access_token;
	            cache::store("redis")->set('component_access_token_'.$appid,$component_access_token,590);
	        }
	        if(!$pre_auth_code = cache::get('pre_auth_code_'.$appid)){
	            $url2 = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$component_access_token;;
	            $data = '{"component_appid":"'.$com_appid.'"}';
	            $res2 = json_decode($this->curl_post($data, $url2));
		        $pre_auth_code = substr($res2->pre_auth_code,14);
		        cache::store("redis")->set('pre_auth_code_'.$appid,$pre_auth_code,590);
		    }
	        $redirect_uri = 'http://'.$verify['redirect_url'].'/man/auth/getAccessToken/pid/'.$pid.'/appid/'.$appid.'/com_appid/'.$com_appid;
	        $url3 = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$com_appid.'&pre_auth_code='.$pre_auth_code.'&redirect_uri='.$redirect_uri;

	        $this->assign('url',$url3);
	        return $this->fetch('show');
	}

	public function getAccessToken(){
		$appid = input('appid');
		$com_appid = input('com_appid');
		$pid = input('pid');
		$verify = Db::name('auth_account')->where('com_appid',$com_appid)->find();
		if (!$component_access_token = cache::get('component_access_token_'.$appid)){
            $data = '{"component_appid":"'.$com_appid.'","component_appsecret":"'.$verify['component_appsecret'].'","component_verify_ticket":"'.$verify['ComponentVerifyTicket'].'"}';
            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
            $res = json_decode($this->curl_post($data, $url));
            $component_access_token = $res->component_access_token;
            cache::store("redis")->set('component_access_token_'.$appid,$component_access_token,590);
        }
        $auth_code = substr(input('auth_code'),16);
        $url2 = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$component_access_token;
		$data = '{"component_appid":"'.$com_appid.'","authorization_code":"'.$auth_code.'"}';
        $res2 =  json_decode($this->curl_post($data, $url2));
        $authorizer_refresh_token = substr($res2->authorization_info->authorizer_refresh_token,15);
        $res_arr = array(
            'authorizer_access_token'=> $res2->authorization_info->authorizer_access_token,
            'authorizer_refresh_token'=> $authorizer_refresh_token
        );
        $result = Db::table('aicece_auth_account')->where('com_appid',$com_appid)->update($res_arr);
        $wechat = array('appid'=>$appid,'pid'=>$pid,'authorizer_refresh_token'=>$authorizer_refresh_token,'status'=>1);
        Db::name('wechat_auth')->insert($wechat);

        if($result){
        	echo "授权成功";
        }else{
        	echo "授权失败";
        }
	}

	public function add(){
		return $this->fetch('add');
	}


	public function doadd(){
		$instance = Request::instance();
		if($instance->isPost()){
			$data = $instance->post();
			//验证当前服务器ip是否已经存在
			$ret = Db::name("auth_account")->where("server_ip",trim($data['server_ip']))->find();
			if($ret){
				$this->error('源码服务器ip已经存在',url('man/auth/add'), 3);exit();
			}
			$result = Db::name("auth_account")->insert($data);
			if($result){
				//向远程服务器写入配置信息
				$writeData = array(
						"encodingAesKey"=>trim($data['encodingAesKey']),
						"token"=>trim($data['token']),
						"component_appid"=>trim($data['com_appid']),
						"component_appsecret"=>trim($data['component_appsecret']),
						"api_domain"=>trim($data['redirect_url']),
				);
				$writeUrl = "http://{$data['server_ip']}/wx/writeRule.php";
				self::curl_post($writeData, $writeUrl);
				$this->success('添加成功', url('man/auth/index'), 3);
			}else{
				$this->error('添加失败');
			}
		}
	}
	
	public function curl_post($data, $url) {
		$curl = curl_init ();
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $curl, CURLOPT_TIMEOUT, 500 );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt ( $curl, CURLOPT_URL, $url );
		curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, "POST" );
		curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
		$res = curl_exec ( $curl );
		curl_close ( $curl );
		return $res;
	}
	
	public function edit(){
		$id = input('id');
		$instance = Request::instance();
		if($instance->isPost()){
			$data=$instance->post();
			$res=Db::name('auth_account')->where('id',$id)->update($data);
	        if($res){
	        	//向远程服务器写入配置信息
	        	$writeData = array(
	        			"encodingAesKey"=>trim($data['encodingAesKey']),
	        			"token"=>trim($data['token']),
	        			"component_appid"=>trim($data['com_appid']),
	        			"component_appsecret"=>trim($data['component_appsecret']),
	        			"api_domain"=>trim($data['redirect_url']),
	        	);
	        	$writeUrl = "http://{$data['server_ip']}/wx/writeRule.php";
	        	self::curl_post($writeData, $writeUrl);
				$this->success('修改成功',url('man/auth/index'));
			}else{
				$this->success('修改失败',url('man/auth/index'));
			}
		}
		$data =Db::name('auth_account')->where('id',$id)->find();
		$this->assign('data',$data);
		return $this->fetch('edit');
	}

	public function delete(){
		$id = input('id');
		$res = Db::name('auth_account')->where('id',$id)->delete();

		if($res){
			$this->success('删除成功',url('man/auth/index'));
		}else{
			$this->success('删除失败',url('man/auth/index'));
		}
	}
	public function delete_wechat(){
		$id = input('id');
		$res = Db::name('wechat_auth')->where('id',$id)->delete();

		if($res){
			$this->success('删除成功',url('man/auth/wechat'));
		}else{
			$this->success('删除失败',url('man/auth/wechat'));
		}
	}

	public function wechat_add(){
		$request = Request::instance();
		if($request->isPost()){
			$post = $request->post();
			$list = explode("\n", $post['appids']);
			foreach($list as $k=>$val){
				$data[$k]['pid']=$post['pid'];
				$data[$k]['appid']=trim($val);
				$data[$k]['status']=1;
			}
			$result = Db::name('wechat_auth')->insertAll($data);
			if($result){
				$this->success('添加成功', url('man/auth/wechat'), 3);
			}else{
				$this->success('添加失败');
			}
		}
		return $this->fetch('add_wechat');
	}

	public function change(){
		$aid = input('aid');
		$status = input('status');
		if($status==2){
			$res = Db::name("wechat_auth")->where('id',$aid)->update(['status'=>$status,'start_time'=>date("Y-m-d H:i:s")]);
		}else{
			$res = Db::name("wechat_auth")->where('id',$aid)->update(['status'=>$status]);
		}
		if($status==3){
			$res = Db::name("wechat_auth")->where('id',$aid)->update(['status'=>$status,'end_time'=>date("Y-m-d H:i:s")]);
		}else{
			$res = Db::name("wechat_auth")->where('id',$aid)->update(['status'=>$status]);
		}
		if($status ==1){
			$res = Db::name("wechat_auth")->where('id',$aid)->update(['status'=>$status,'start_time'=>'','end_time'=>'']);
		}
		$options = [
            'type'  =>  $this->GetCache(), 
            'expire'=>  600,
            'prefix'=>  'think',
            'host'  =>  '127.0.0.1',
            'port'  => '6379'
        ];
        Cache::connect($options);
		cache::rm('osman_vendor_mp');
		return true;
	}
	private function GetCache(){
    	$cache = 'redis';
		if(Request::instance()->domain()=='http://osman.cn'){
			$cache = 'file';
		}
		return $cache;
    }
}